<template>
    <el-card class="card">
        <el-form :model="form" label-width="auto" style="max-width: 300px">
            <el-form-item label="用户名">
                <el-input placeholder="请输入用户名进行查询" v-model="form.name" />
            </el-form-item>
        </el-form>
        <el-button type="primary" style="margin-left: 10px">搜索</el-button>
    </el-card>

    <el-card>
        <div style="display: flex;">
            <el-button type="primary" style="margin-right: 10px" @click="showDialog">添加</el-button>
            <el-dialog v-model="dialogVisible" :title="userInfo.id ? '更新用户' : '添加用户'" width="500">
                <el-form :model="userInfo">
                    <el-form-item label="用户姓名">
                        <el-input v-model="userInfo.username"></el-input>
                    </el-form-item>
                    <el-form-item label="用户昵称">
                        <el-input v-model="userInfo.name"></el-input>
                    </el-form-item>
                    <el-form-item label="用户密码" v-if="!userInfo.id">
                        <el-input v-model="userInfo.password"></el-input>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="confirm">
                            确定
                        </el-button>
                    </div>
                </template>
            </el-dialog>
            <el-button type="danger" style="margin-left: 10px">批量删除</el-button>
        </div>
        <el-table :data="tableData" style="width: 100%">
            <!-- <el-table-column type="index" label="序号" /> -->
            <el-table-column prop="id" label="id" />
            <el-table-column prop="username" label="用户名字" />
            <el-table-column prop="name" label="用户名称" width="180" />
            <el-table-column prop="roleName" label="用户角色" />
            <el-table-column prop="createTime" label="创建时间" />
            <el-table-column prop="updateTime" label="更新时间" />
            <el-table-column fixed="right" label="Operations" min-width="180px">
                <template #="{ row }">
                    <el-button type="primary" size="small" @click="clickAssignRoles(row)">分配角色</el-button>
                    <el-button type="primary" size="small" @click="updateUser(row)">编辑</el-button>
                    <el-button type="primary" size="small" @click="deleteSingle(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
            layout="prev, pager, next, sizes, total" :total="totalSize" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
    </el-card>

    <el-dialog v-model="dialogVisible2" title="分配角色" width="500">
        <el-form :model="userInfo2">
            <el-form-item label="用户姓名">
                <el-input v-model="userInfo2.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="职位列表">
                <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">
                    Check all
                </el-checkbox>
                <el-checkbox-group v-model="checkedRoles" @change="handleCheckedCitiesChange">
                    <el-checkbox v-for="(role,index) in allRoles" :key="index" :label="role" :value="role">
                        {{ role.roleName }}
                    </el-checkbox>
                </el-checkbox-group>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible2 = false">取消</el-button>
                <el-button type="primary" @click="confirm2">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { addUsers, assignRoles, deleteUsers, getRolesByUsers, getUsersList, updateUsersInfo } from '../../../api/user';
import { ElMessage } from 'element-plus';

const checkAll = ref(false)
const isIndeterminate = ref(true)
let checkedRoles = ref<any>([])
let allRoles = ref<any>([])

const handleCheckAllChange = (val: boolean) => {
  checkedRoles.value = val ? allRoles.value : []
  isIndeterminate.value = false
}
const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === allRoles.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < allRoles.value.length
}

const userInfo = reactive<any>({
    username: '',
    name: '',
    password: ''
})
const userInfo2 = reactive<any>({
    username: '',
    id: 0
})
const confirm = async () => {
    if (userInfo.id) {
        await updateUsersInfo(userInfo)
    } else {
        await addUsers(userInfo)
    }
    dialogVisible.value = false
    getUsers()
    // window.location.reload() //加上，防止修改当前登录的用户名，就需要重新获取登录信息再展示，因此强制刷新一下即可
}
const updateUser = (row: any) => {
    dialogVisible.value = true
    Object.assign(userInfo, row)
}

const deleteSingle = async(row: any) => {
    let result = await deleteUsers(row.id)
    if (result.code == 200) {
        ElMessage({type: 'success', message: '删除成功'})
        getUsers()
    }
}

const confirm2 = async () => {
    console.log(checkedRoles, userInfo2)
    let data = {
        roleIdList: checkedRoles.value.map((item: { id: any; }) => item.id),
        userId: userInfo2.id
    }
    let result = await assignRoles(data)
    if (result.code == 200) {
        ElMessage({type: 'success', message: '分配角色成功'})
        dialogVisible2.value = false
        getUsers()
    }
}

const clickAssignRoles = async (row: any) => {
    Object.assign(userInfo2, row)
    let result = await getRolesByUsers(row.id)
    allRoles.value = result.data.allRolesList
    checkedRoles.value = result.data.assignRoles
    dialogVisible2.value = true
}

const dialogVisible = ref(false)
const dialogVisible2 = ref(false)

const showDialog = () => {
    dialogVisible.value = true
    Object.assign(userInfo, {
        id: 0,
        username: '',
        name: '',
        password: ''
    })
}

let currentPage = ref(1)
let pageSize = ref(10)
let totalSize = ref(0)

const handleSizeChange = () => {
    getUsers()
}
const handleCurrentChange = () => {
    getUsers()
}

const form = reactive({
    name: ''
})

let tableData = ref<any>([])

const getUsers = async () => {
    let result = await getUsersList(currentPage.value, pageSize.value)
    if (result.code == 200) {
        totalSize.value = result.data.total
        tableData.value = result.data.records
    }
}

onMounted(async () => {
    await getUsers()
})

</script>

<style scoped lang="scss">
.card {
    :deep(.el-card__body) {
        display: flex;
    }
}
</style>